<?php
  $this->headTitle($this->title);
  $this->headLink()->appendStylesheet(Zend_Registry::get('static_path').'css/user.css');
  $this->headLink()->appendStylesheet(Zend_Registry::get('static_path').'css/frontierCalendar/jquery-frontier-cal-1.3.2.css');
  $this->headLink()->appendStylesheet(Zend_Registry::get('static_path').'css/colorpicker/colorpicker.css');
  $this->headLink()->appendStylesheet(Zend_Registry::get('static_path').'css/jquery-ui/smoothness/jquery-ui-1.8.1.custom.css');

  $this->headScript()->appendFile(Zend_Registry::get('static_path').'js/jquery-ui/smoothness/jquery-ui-1.8.1.custom.min.js');
  $this->headScript()->appendFile(Zend_Registry::get('static_path').'js/colorpicker/colorpicker.js');
  $this->headScript()->appendFile(Zend_Registry::get('static_path').'js/lib/jshashtable-2.1.js');
  $this->headScript()->appendFile(Zend_Registry::get('static_path').'js/jquery-qtip-1.0.0-rc3140944/jquery.qtip-1.0.js');
  $this->headScript()->appendFile(Zend_Registry::get('static_path').'js/frontierCalendar/jquery-frontier-cal-1.3.2.js');

  $this->layout()->setLayout('userlayout');
?>
<div class="nav"><a href="<?php echo $this->url(array( 'controller' => 'admin', 'action'     => 'index'),'default', true) ?>" class="navlink">Control Panel</a><img src="../images/arrow.gif" class="arrow"/> Calendar & Events</div>

<!-- Some CSS for our example. (Not required for calendar plugin. Used for example.)-->
<style type="text/css" media="screen">

.shadow {
	-moz-box-shadow: 3px 3px 4px #aaaaaa;
	-webkit-box-shadow: 3px 3px 4px #aaaaaa;
	box-shadow: 3px 3px 4px #aaaaaa;
	/* For IE 8 */
	-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#aaaaaa')";
	/* For IE 5.5 - 7 */
	filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#aaaaaa');
}
</style>

<script type="text/javascript">
$(document).ready(function(){

	var clickDate = "";
	var clickAgendaItem = "";
        var currentDate="";

        if($("#dateSelect").val() ==""){
            var d= new Date();
            currentDate = d.getFullYear()+"-" +(d.getMonth()+1) +"-"+ d.getDate() ;
        }else{
            currentDate = $("#dateSelect").val() ;
        }
       $.ajax({
                  type: "POST",
                  url:  path+"calendar/get",
                  dataType: 'json',
                  data: {startDate:currentDate},
                  cache: true,
                  success: function(data){
                     $.each(data, function(i, item) {
                         var arr1 = item._startTime.split(":");
                         var arr2 = item._endTime.split(":");
                        var startDateObj = new Date(parseInt(item._startDate.substring(0,4)),parseInt(item._startDate.substring(5,7))-1,parseInt(item._startDate.substring(8,10)),arr1[0] ,arr1[1],0,0);
			var endDateObj = new Date(parseInt(item._endDate.substring(0,4)),parseInt(item._endDate.substring(5,7))-1,parseInt(item._endDate.substring(8,10)),arr2[0],arr2[1],0,0);
                        jfcalplugin.addAgendaItem(
                                "#mycal",
                                item._description,
                                startDateObj,
                                endDateObj,
                                false,
                                {
                                    eventId:item._eventId
                                },
                                {
                                        backgroundColor: item._background,
                                        foregroundColor: item._foreground
                                }
                           );
                     });
                }
            });

	/**
	 * Initializes calendar with current year & month
	 * specifies the callbacks for day click & agenda item click events
	 * then returns instance of plugin object
	 */
	var jfcalplugin = $("#mycal").jFrontierCal({
		date: new Date(),
		dayClickCallback: myDayClickHandler,
		agendaClickCallback: myAgendaClickHandler,
		agendaDropCallback: myAgendaDropHandler,
		agendaMouseoverCallback: myAgendaMouseoverHandler,
		applyAgendaTooltipCallback: myApplyTooltip,
		agendaDragStartCallback : myAgendaDragStart,
		agendaDragStopCallback : myAgendaDragStop,
		dragAndDropEnabled: false
	}).data("plugin");

	/**
	 * Do something when dragging starts on agenda div
	 */
	function myAgendaDragStart(eventObj,divElm,agendaItem){
		// destroy our qtip tooltip
		if(divElm.data("qtip")){
			divElm.qtip("destroy");
		}
	};

	/**
	 * Do something when dragging stops on agenda div
	 */
	function myAgendaDragStop(eventObj,divElm,agendaItem){
		//alert("drag stop");
	};

	/**
	 * Custom tooltip - use any tooltip library you want to display the agenda data.
	 * for this example we use qTip - http://craigsworks.com/projects/qtip/
	 *
	 * @param divElm - jquery object for agenda div element
	 * @param agendaItem - javascript object containing agenda data.
	 */
	function myApplyTooltip(divElm,agendaItem){

		// Destroy currrent tooltip if present
		if(divElm.data("qtip")){
			divElm.qtip("destroy");
		}

		var displayData = "";

		var title = agendaItem.title;
		var startDate = agendaItem.startDate;
		var endDate = agendaItem.endDate;
		var allDay = agendaItem.allDay;
		var data = agendaItem.data;
		displayData += "<br><b>" + title+ "</b><br><br>";
		if(allDay){
			displayData += "(All day event)<br><br>";
		}else{
			displayData += "<b>Starts:</b> " + startDate + "<br>" + "<b>Ends:</b> " + endDate + "<br><br>";
		}
		for (var propertyName in data) {
			displayData += "<input type='hidden' id='" + propertyName + "' value='" + data[propertyName] + "'/>"
		}
		// use the user specified colors from the agenda item.
		var backgroundColor = agendaItem.displayProp.backgroundColor;
		var foregroundColor = agendaItem.displayProp.foregroundColor;
		var myStyle = {
			border: {
				width: 5,
				radius: 10
			},
			padding: 10,
			textAlign: "left",
			tip: true,
			name: "dark" // other style properties are inherited from dark theme
		};
		if(backgroundColor != null && backgroundColor != ""){
			myStyle["backgroundColor"] = backgroundColor;
		}
		if(foregroundColor != null && foregroundColor != ""){
			myStyle["color"] = foregroundColor;
		}
		// apply tooltip
		divElm.qtip({
			content: displayData,
			position: {
				corner: {
					tooltip: "bottomMiddle",
					target: "topMiddle"
				},
				adjust: {
					mouse: true,
					x: 0,
					y: -15
				},
				target: "mouse"
			},
			show: {
				when: {
					event: 'mouseover'
				}
			},
			style: myStyle
		});

	};

	/**
	 * Make the day cells roughly 3/4th as tall as they are wide. this makes our calendar wider than it is tall.
	 */
	jfcalplugin.setAspectRatio("#mycal",0.75);

	/**
	 * Called when user clicks day cell
	 * use reference to plugin object to add agenda item
	 */
	function myDayClickHandler(eventObj){
		// Get the Date of the day that was clicked from the event object
		var date = eventObj.data.calDayDate;
		// store date in our global js variable for access later
		clickDate = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
		// open our add event dialog
		$('#add-event-form').dialog('open');
	};

	/**
	 * Called when user clicks and agenda item
	 * use reference to plugin object to edit agenda item
	 */
	function myAgendaClickHandler(eventObj){
		// Get ID of the agenda item from the event object
		var agendaId = eventObj.data.agendaId;
		// pull agenda item from calendar
		var agendaItem = jfcalplugin.getAgendaItemById("#mycal",agendaId);
		clickAgendaItem = agendaItem;
		$("#display-event-form").dialog('open');
	};

	/**
	 * Called when user drops an agenda item into a day cell.
	 */
	function myAgendaDropHandler(eventObj){
		// Get ID of the agenda item from the event object
		var agendaId = eventObj.data.agendaId;
		// date agenda item was dropped onto
		var date = eventObj.data.calDayDate;
		// Pull agenda item from calendar
		var agendaItem = jfcalplugin.getAgendaItemById("#mycal",agendaId);
	};

	/**
	 * Called when a user mouses over an agenda item
	 */
	function myAgendaMouseoverHandler(eventObj){
		var agendaId = eventObj.data.agendaId;
		var agendaItem = jfcalplugin.getAgendaItemById("#mycal",agendaId);
		//alert("You moused over agenda item " + agendaItem.title + " at location (X=" + eventObj.pageX + ", Y=" + eventObj.pageY + ")");
	};
	/**
	 * Initialize jquery ui datepicker. set date format to yyyy-mm-dd for easy parsing
	 */
	$("#dateSelect").datepicker({
		showOtherMonths: true,
		selectOtherMonths: true,
		changeMonth: true,
		changeYear: true,
		showButtonPanel: true,
		dateFormat: 'yy-mm-dd'
	});

	/**
	 * Set datepicker to current date
	 */
	$("#dateSelect").datepicker('setDate', new Date());
	/**
	 * Use reference to plugin object to a specific year/month
	 */
	$("#dateSelect").bind('change', function() {
		var selectedDate = $("#dateSelect").val();
		var dtArray = selectedDate.split("-");
		var year = dtArray[0];
		// jquery datepicker months start at 1 (1=January)
		var month = dtArray[1];
		// strip any preceeding 0's
		month = month.replace(/^[0]+/g,"")
		var day = dtArray[2];
		// plugin uses 0-based months so we subtrac 1
                $.ajax({
                  type: "POST",
                  url:  path+"calendar/get",
                  dataType: 'json',
                  data: {startDate:$("#dateSelect").val()},
                  cache: false,
                  success: function(data){
                     
                     $.each(data, function(i, item) {
                         var arr1 = item._startTime.split(":");
                         var arr2 = item._endTime.split(":");
                        var startDateObj = new Date(parseInt(item._startDate.substring(0,4)),parseInt(item._startDate.substring(5,7))-1,parseInt(item._startDate.substring(8,10)),arr1[0] ,arr1[1],0,0);
			var endDateObj = new Date(parseInt(item._endDate.substring(0,4)),parseInt(item._endDate.substring(5,7))-1,parseInt(item._endDate.substring(8,10)),arr2[0],arr2[1],0,0);
                         jfcalplugin.deleteAgendaItemByDataAttr('#mycal','eventId',item._eventId);
                        jfcalplugin.addAgendaItem(
                                "#mycal",
                                item._description,
                                startDateObj,
                                endDateObj,
                                false,
                                {
                                    eventId:item._eventId
                                },
                                {
                                        backgroundColor: item._background,
                                        foregroundColor: item._foreground
                                }
                           );
                     });
                }
            });
		jfcalplugin.showMonth("#mycal",year,parseInt(month-1).toString());
	});
	/**
	 * Initialize previous month button
	 */
	$("#BtnPreviousMonth").button();
	$("#BtnPreviousMonth").click(function() {
		jfcalplugin.showPreviousMonth("#mycal");
		// update the jqeury datepicker value
		var calDate = jfcalplugin.getCurrentDate("#mycal"); // returns Date object
		var cyear = calDate.getFullYear();
		// Date month 0-based (0=January)
		var cmonth = calDate.getMonth();
		var cday = calDate.getDate();
		// jquery datepicker month starts at 1 (1=January) so we add 1
		$("#dateSelect").datepicker("setDate",cyear+"-"+(cmonth+1)+"-"+cday);
                $.ajax({
                  type: "POST",
                  url:  path+"calendar/get",
                  dataType: 'json',
                  data: {startDate:$("#dateSelect").val()},
                  cache: false,
                  success: function(data){
                     $.each(data, function(i, item) {
                         var arr1 = item._startTime.split(":");
                         var arr2 = item._endTime.split(":");
                        var startDateObj = new Date(parseInt(item._startDate.substring(0,4)),parseInt(item._startDate.substring(5,7))-1,parseInt(item._startDate.substring(8,10)),arr1[0] ,arr1[1],0,0);
			var endDateObj = new Date(parseInt(item._endDate.substring(0,4)),parseInt(item._endDate.substring(5,7))-1,parseInt(item._endDate.substring(8,10)),arr2[0],arr2[1],0,0);
                       jfcalplugin.deleteAgendaItemByDataAttr('#mycal','eventId',item._eventId);
                       jfcalplugin.addAgendaItem(
                                "#mycal",
                                item._description,
                                startDateObj,
                                endDateObj,
                                false,
                                {
                                    eventId:item._eventId
                                },
                                {
                                        backgroundColor: item._background,
                                        foregroundColor: item._foreground
                                }
                           );
                     });
                }
            });
		return false;
	});
	/**
	 * Initialize next month button
	 */
	$("#BtnNextMonth").button();
	$("#BtnNextMonth").click(function() {
		jfcalplugin.showNextMonth("#mycal");
		// update the jqeury datepicker value
		var calDate = jfcalplugin.getCurrentDate("#mycal"); // returns Date object
		var cyear = calDate.getFullYear();
		// Date month 0-based (0=January)
		var cmonth = calDate.getMonth();
		var cday = calDate.getDate();
		// jquery datepicker month starts at 1 (1=January) so we add 1
		$("#dateSelect").datepicker("setDate",cyear+"-"+(cmonth+1)+"-"+cday);
                $.ajax({
                  type: "POST",
                  url:  path+"calendar/get",
                  dataType: 'json',
                  data: {startDate:$("#dateSelect").val()},
                  cache: false,
                  success: function(data){
                     $.each(data, function(i, item) {
                         var arr1 = item._startTime.split(":");
                         var arr2 = item._endTime.split(":");
                        var startDateObj = new Date(parseInt(item._startDate.substring(0,4)),parseInt(item._startDate.substring(5,7))-1,parseInt(item._startDate.substring(8,10)),arr1[0] ,arr1[1],0,0);
			var endDateObj = new Date(parseInt(item._endDate.substring(0,4)),parseInt(item._endDate.substring(5,7))-1,parseInt(item._endDate.substring(8,10)),arr2[0],arr2[1],0,0);
                        jfcalplugin.deleteAgendaItemByDataAttr('#mycal','eventId',item._eventId);
                        jfcalplugin.addAgendaItem(
                                "#mycal",
                                item._description,
                                startDateObj,
                                endDateObj,
                                false,
                                {
                                    eventId:item._eventId
                                },
                                {
                                        backgroundColor: item._background,
                                        foregroundColor: item._foreground
                                }
                           );
                     });
                }
            });
		return false;
	});

	/**
	 * Initialize add event modal form
	 */
	$("#add-event-form").dialog({
		autoOpen: false,
		height: 400,
		width: 400,
		modal: true,
		buttons: {
			'Add Event': function() {

				var what = jQuery.trim($("#what").val());

				if(what == ""){
					alert("Please enter a short event description into the \"Event\" field.");
				}else{

					var startDate = $("#startDate").val();
					var startDtArray = startDate.split("-");
					var startYear = startDtArray[0];
					// jquery datepicker months start at 1 (1=January)
					var startMonth = startDtArray[1];
					var startDay = startDtArray[2];
					// strip any preceeding 0's
					startMonth = startMonth.replace(/^[0]+/g,"");
					startDay = startDay.replace(/^[0]+/g,"");
					var startHour = jQuery.trim($("#startHour").val());
					var startMin = jQuery.trim($("#startMin").val());
					var startMeridiem = jQuery.trim($("#startMeridiem").val());
					startHour = parseInt(startHour.replace(/^[0]+/g,""));
					if(startMin == "0" || startMin == "00"){
						startMin = 0;
					}else{
						startMin = parseInt(startMin.replace(/^[0]+/g,""));
					}
					if(startMeridiem == "AM" && startHour == 12){
						startHour = 0;
					}else if(startMeridiem == "PM" && startHour < 12){
						startHour = parseInt(startHour) + 12;
					}

					var endDate = $("#endDate").val();
					var endDtArray = endDate.split("-");
					var endYear = endDtArray[0];
					// jquery datepicker months start at 1 (1=January)
					var endMonth = endDtArray[1];
					var endDay = endDtArray[2];
					// strip any preceeding 0's
					endMonth = endMonth.replace(/^[0]+/g,"");

					endDay = endDay.replace(/^[0]+/g,"");
					var endHour = jQuery.trim($("#endHour").val());
					var endMin = jQuery.trim($("#endMin").val());
					var endMeridiem = jQuery.trim($("#endMeridiem").val());
					endHour = parseInt(endHour.replace(/^[0]+/g,""));
					if(endMin == "0" || endMin == "00"){
						endMin = 0;
					}else{
						endMin = parseInt(endMin.replace(/^[0]+/g,""));
					}
					if(endMeridiem == "AM" && endHour == 12){
						endHour = 0;
					}else if(endMeridiem == "PM" && endHour < 12){
						endHour = parseInt(endHour) + 12;
					}

					//alert("Start time: " + startHour + ":" + startMin + " " + startMeridiem + ", End time: " + endHour + ":" + endMin + " " + endMeridiem);

					// Dates use integers
					var startDateObj = new Date(parseInt(startYear),parseInt(startMonth)-1,parseInt(startDay),startHour,startMin,0,0);
					var endDateObj = new Date(parseInt(endYear),parseInt(endMonth)-1,parseInt(endDay),endHour,endMin,0,0);

                                        var startDate=startYear+"/"+startMonth+"/"+startDay;
                                        var startTime=startHour+":"+startMin;
                                        var endTime=endHour+":"+endMin;
                                        var endDate=endYear+"/"+endMonth+"/"+endDay;
					// add new event to the calendar

                                        if ( Math.round((endDateObj.getTime() - startDateObj.getTime()) / 1000) < 0){
					  alert("Sorry, you can't create an event that ends before it starts");
					  return;
				          }

                                        $.ajax({
                                              type: "POST",
                                              url:   path+"calendar/add",
                                              data: {description:what,startDate:startDate, startTime: startTime,endDate:endDate,endTime: endTime,background:$("#colorBackground").val(),foreground:$("#colorForeground").val()},
                                              cache: false,
                                              success: function(html){;
                                                  if(html !="N"){
                                                          jfcalplugin.addAgendaItem(
                                                        "#mycal",
                                                        what,
                                                        startDateObj,
                                                        endDateObj,
                                                        false,
                                                        {
                                                            eventId: html
                                                        },
                                                        {
                                                                backgroundColor: $("#colorBackground").val(),
                                                                foregroundColor: $("#colorForeground").val()
                                                        }
                                                        );
                                       
                                                }else{
                                                   alert("Error adding the event");
                                                }
                                            }
                                            
                                        });
                                      $(this).dialog('close');
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		open: function(event, ui){
			// initialize start date picker
			$("#startDate").datepicker({
				showOtherMonths: true,
				selectOtherMonths: true,
				changeMonth: true,
				changeYear: true,
				showButtonPanel: true,
				dateFormat: 'yy-mm-dd'
			});
			// initialize end date picker
			$("#endDate").datepicker({
				showOtherMonths: true,
				selectOtherMonths: true,
				changeMonth: true,
				changeYear: true,
				showButtonPanel: true,
				dateFormat: 'yy-mm-dd'
			});
			// initialize with the date that was clicked
			$("#startDate").val(clickDate);
			$("#endDate").val(clickDate);
			// initialize color pickers
			$("#colorSelectorBackground").ColorPicker({
				color: "#333333",
				onShow: function (colpkr) {
					$(colpkr).css("z-index","10000");
					$(colpkr).fadeIn(500);
					return false;
				},
				onHide: function (colpkr) {
					$(colpkr).fadeOut(500);
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					$("#colorSelectorBackground div").css("backgroundColor", "#" + hex);
					$("#colorBackground").val("#" + hex);
				}
			});
			//$("#colorBackground").val("#1040b0");
			$("#colorSelectorForeground").ColorPicker({
				color: "#ffffff",
				onShow: function (colpkr) {
					$(colpkr).css("z-index","10000");
					$(colpkr).fadeIn(500);
					return false;
				},
				onHide: function (colpkr) {
					$(colpkr).fadeOut(500);
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					$("#colorSelectorForeground div").css("backgroundColor", "#" + hex);
					$("#colorForeground").val("#" + hex);
				}
			});
			//$("#colorForeground").val("#ffffff");
			// put focus on first form input element
			$("#what").focus();
		},
		close: function() {
			// reset form elements when we close so they are fresh when the dialog is opened again.
			$("#startDate").datepicker("destroy");
			$("#endDate").datepicker("destroy");
			$("#startDate").val("");
			$("#endDate").val("");
			$("#startHour option:eq(0)").attr("selected", "selected");
			$("#startMin option:eq(0)").attr("selected", "selected");
			$("#startMeridiem option:eq(0)").attr("selected", "selected");
			$("#endHour option:eq(0)").attr("selected", "selected");
			$("#endMin option:eq(0)").attr("selected", "selected");
			$("#endMeridiem option:eq(0)").attr("selected", "selected");
			$("#what").val("");
			//$("#colorBackground").val("#1040b0");
			//$("#colorForeground").val("#ffffff");
		}
	});

        $("#edit-event-form").dialog({
		autoOpen: false,
		height: 400,
		width: 400,
		modal: true,
		buttons: {
                    'Update Event': function() {
                        var startTime=$("#_startHour").val()+":"+$("#_startMin").val();
                        var endTime=$("#_endHour").val()+":"+$("#_endMin").val();
                             $.ajax({
                                              type: "POST",
                                              url:   path+"calendar/update",
                                              data: {eventId:$("#_eventId").val(),description:$("#_what").val(),startDate:$("#_startDate").val(), startTime: startTime,endDate:$("#_endDate").val(),endTime: endTime,background:$("#_colorBackground").val(),foreground:$("#_colorForeground").val()},
                                              cache: false,
                                              success: function(html){
                                                  if(html !="N"){
                                                    var startDate = $("#_startDate").val();
                                                    var startDtArray = startDate.split("-");
                                                    var startYear = startDtArray[0];
                                                    // jquery datepicker months start at 1 (1=January)
                                                    var startMonth = startDtArray[1];
                                                    var startDay = startDtArray[2];
                                                    // strip any preceeding 0's
                                                    startMonth = startMonth.replace(/^[0]+/g,"");
                                                    startDay = startDay.replace(/^[0]+/g,"");
                                                    var startHour = jQuery.trim($("#_startHour").val());
                                                    var startMin = jQuery.trim($("#_startMin").val());
                                                    var startMeridiem = jQuery.trim($("#_startMeridiem").val());
                                                    startHour = parseInt(startHour.replace(/^[0]+/g,""));
                                                    if(startMin == "0" || startMin == "00"){
                                                            startMin = 0;
                                                    }else{
                                                            startMin = parseInt(startMin.replace(/^[0]+/g,""));
                                                    }
                                                    if(startMeridiem == "AM" && startHour == 12){
                                                            startHour = 0;
                                                    }else if(startMeridiem == "PM" && startHour < 12){
                                                            startHour = parseInt(startHour) + 12;
                                                    }

                                                    var endDate = $("#_endDate").val();
                                                    var endDtArray = endDate.split("-");
                                                    var endYear = endDtArray[0];
                                                    // jquery datepicker months start at 1 (1=January)
                                                    var endMonth = endDtArray[1];
                                                    var endDay = endDtArray[2];
                                                    // strip any preceeding 0's
                                                    endMonth = endMonth.replace(/^[0]+/g,"");

                                                    endDay = endDay.replace(/^[0]+/g,"");
                                                    var endHour = jQuery.trim($("#_endHour").val());
                                                    var endMin = jQuery.trim($("#_endMin").val());
                                                    var endMeridiem = jQuery.trim($("#_endMeridiem").val());
                                                    endHour = parseInt(endHour.replace(/^[0]+/g,""));
                                                    if(endMin == "0" || endMin == "00"){
                                                            endMin = 0;
                                                    }else{
                                                            endMin = parseInt(endMin.replace(/^[0]+/g,""));
                                                    }
                                                    if(endMeridiem == "AM" && endHour == 12){
                                                            endHour = 0;
                                                    }else if(endMeridiem == "PM" && endHour < 12){
                                                            endHour = parseInt(endHour) + 12;
                                                    }

                                                    //alert("Start time: " + startHour + ":" + startMin + " " + startMeridiem + ", End time: " + endHour + ":" + endMin + " " + endMeridiem);

                                                    // Dates use integers
                                                    var startDateObj = new Date(parseInt(startYear),parseInt(startMonth)-1,parseInt(startDay),startHour,startMin,0,0);
                                                    var endDateObj = new Date(parseInt(endYear),parseInt(endMonth)-1,parseInt(endDay),endHour,endMin,0,0);

                                                       jfcalplugin.deleteAgendaItemById("#mycal",clickAgendaItem.agendaId);
                                                       
                                                       jfcalplugin.addAgendaItem(
                                                        "#mycal",
                                                        $("#_what").val(),
                                                        startDateObj,
                                                        endDateObj,
                                                        false,
                                                        {
                                                            eventId: $("#_eventId").val()
                                                        },
                                                        {
                                                                backgroundColor: $("#_colorBackground").val(),
                                                                foregroundColor:$("#_colorForeground").val()
                                                        }
                                                        );

                                                }else{
                                                   alert("Error updating the event");
                                                }
                                            }

                                        });
                                      $(this).dialog('close');

                },
                "Cancel" :function(){
                    $(this).dialog('close');
                }
            }
        });
	/**
	 * Initialize display event form.
	 */
	$("#display-event-form").dialog({
		autoOpen: false,
		height: 400,
		width: 400,
		modal: true,
		buttons: {
			Cancel: function() {
				$(this).dialog('close');
			},
			'Edit': function() {
                          var title = clickAgendaItem.title;
                          var startDate = clickAgendaItem.startDate;
                          var endDate = clickAgendaItem.endDate;
                          var allDay = clickAgendaItem.allDay;

                          var startHour = (startDate.getHours() > 12) ?startDate.getHours() -12 : startDate.getHours();
                          var endHour =(endDate.getHours() > 12) ?endDate.getHours() -12 : endDate.getHours();

                          startHour = (startHour==0?12:startHour);
                          endHour = (endHour==0?12:endHour);

       
                           $(this).dialog('close');
                           $("#edit-event-form").dialog('open');
                           $("#_eventId").val(clickAgendaItem.data['eventId']);
                           $("#_what").val(title);

                           $("#_startDate").datepicker({
				showOtherMonths: true,
				selectOtherMonths: true,
				changeMonth: true,
				changeYear: true,
				showButtonPanel: true,
				dateFormat: 'yy-mm-dd'
			});
			// initialize end date picker
			$("#_endDate").datepicker({
				showOtherMonths: true,
				selectOtherMonths: true,
				changeMonth: true,
				changeYear: true,
				showButtonPanel: true,
				dateFormat: 'yy-mm-dd'
			});

                           $("#_startDate").val(startDate.getFullYear()+"-"+ (startDate.getMonth()+1) +"-"+startDate.getDate());
                           $("#_endDate").val(endDate.getFullYear()+"-"+  (endDate.getMonth()+1)+"-"+endDate.getDate());

                    
                           $("#_startHour").val(startHour);
                           $("#_endHour").val(endHour);

   
                           $("#_startMin").val(startDate.getMinutes());
                           $("#_endMin").val(endDate.getMinutes());


                           $("#_startMeridiem").val((startDate.getHours() > 12)? "PM" : "AM");
                           $("#_endMeridiem").val((endDate.getHours() > 12)? "PM" : "AM");

                           
                           $("#_colorBackground").val(clickAgendaItem.displayProp['backgroundColor']);
                           $("#_colorForeground").val(clickAgendaItem.displayProp['foregroundColor']);

                           $("#_colorSelectorBackground").html('<div style="background-color:'+clickAgendaItem.displayProp['backgroundColor']+'; width:30px; height:30px; border: 2px solid #000000;"></div>');
                           $("#_colorSelectorForeground").html('<div style="background-color: '+clickAgendaItem.displayProp['foregroundColor']+'; width:30px; height:30px; border: 2px solid #000000;"></div>');


                           $("#_colorSelectorBackground").ColorPicker({
				color: clickAgendaItem.displayProp['backgroundColor'],
				onShow: function (colpkr) {
					$(colpkr).css("z-index","10000");
					$(colpkr).fadeIn(500);
					return false;
				},
				onHide: function (colpkr) {
					$(colpkr).fadeOut(500);
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					$("#_colorSelectorBackground div").css("backgroundColor", "#" + hex);
					$("#_colorBackground").val("#" + hex);
				}
			});

			$("#_colorSelectorForeground").ColorPicker({
				color:clickAgendaItem.displayProp['foregroundColor'],
				onShow: function (colpkr) {
					$(colpkr).css("z-index","10000");
					$(colpkr).fadeIn(500);
					return false;
				},
				onHide: function (colpkr) {
					$(colpkr).fadeOut(500);
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					$("#_colorSelectorForeground div").css("backgroundColor", "#" + hex);
					$("#_colorForeground").val("#" + hex);
				}
			});



			  $("#_what").focus();
			},
			'Delete': function() {
				if(confirm("Are you sure you want to delete this agenda item?")){
					if(clickAgendaItem != null){
                                                   $.ajax({
                                                                      type: "POST",
                                                                      url:   path+"calendar/delete",
                                                                      data: {eventId:clickAgendaItem.data['eventId']},
                                                                      cache: false,
                                                                      success: function(data){
                                                                           if(data=="Y"){
                                                                               jfcalplugin.deleteAgendaItemById("#mycal",clickAgendaItem.agendaId);
                                                                           }else{
                                                                               alert("Error in deleting the event.");
                                                                           }
                                                                      }
                                                                });
					}
					$(this).dialog('close');
				}
			}
		},
		open: function(event, ui){
			if(clickAgendaItem != null){
				var title = clickAgendaItem.title;
				var startDate = clickAgendaItem.startDate;
				var endDate = clickAgendaItem.endDate;
				var allDay = clickAgendaItem.allDay;
				var data = clickAgendaItem.data;

                                var day=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
                                var month =["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                                var startMin =(parseInt(startDate.getMinutes()) < 10) ? ("0"+ startDate.getMinutes()) : startDate.getMinutes();
                                var endMin =(parseInt(endDate.getMinutes()) < 10) ? ("0"+ endDate.getMinutes()) : endDate.getMinutes();
				// in our example add agenda modal form we put some fake data in the agenda data. we can retrieve it here.
				$("#display-event-form").append(
					"<br><b>" + title+ "</b><br><br>"
				);
				if(allDay){
					$("#display-event-form").append(
						"(All day event)<br><br>"
					);
				}else{
					$("#display-event-form").append(
						"<b>Starts:</b> " +day[startDate.getDay()] +"   "+ month[startDate.getMonth()]     +"  "+ (startDate.getMonth()+1)  +"/"+startDate.getDate() +"/"+startDate.getFullYear() +"   "+
                                                    ((startDate.getHours() >12) ? startDate.getHours() -12 : startDate.getHours()) +":"+startMin+"  "+((startDate.getHours() >12) ? "PM" : "AM")
                                                    +"<br>" +
						"<b>Ends:</b> " + day[endDate.getDay()] +"   "+ month[endDate.getMonth()]     +"  "+(endDate.getMonth()+1)  +"/"+endDate.getDate() +"/"+endDate.getFullYear() +"   "+
                                                    ((endDate.getHours() >12) ? endDate.getHours() -12 : endDate.getHours()) +":"+endMin+"  "+((endDate.getHours() >12) ? "PM" : "AM") + "<br><br>"
                                      //      
					);
				}
				for (var propertyName in data) {
					$("#display-event-form").append("<input type='hidden' id='" + propertyName + "' value='" + data[propertyName] + "'");
				}
			}
		},
		close: function() {
			// clear agenda data
			$("#display-event-form").html("");
		}
	});


});

</script>
<br><br>

		<div id="example" style="margin: auto; width:90%;">

		<div id="toolbar"  style="padding:3px; vertical-align: middle; white-space:nowrap; overflow: hidden;">
			<button id="BtnPreviousMonth">Previous Month</button>
			<button id="BtnNextMonth">Next Month</button>
			&nbsp;&nbsp;&nbsp;
			Date: <input type="text" id="dateSelect" size="20"/>
		</div>

		<br>
		<div id="mycal"></div>

		</div>


		<div id="add-event-form" title="Add New Event">
			<p class="validateTips">All form fields are required.</p>
			<form>
			<fieldset>
				<label for="name">Event</label>
				<input type="text" name="what" id="what" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;"/>
				<table style="width:100%; padding:5px;">
					<tr>
						<td>
							<label>Start Date</label>
							<input type="text" name="startDate" id="startDate" value="" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;"/>
						</td>
						<td>&nbsp;</td>
						<td>
							<label>Hour</label>
							<select id="startHour" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="12">12</option>
								<option value="1">1</option>
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="4">4</option>
								<option value="5">5</option>
								<option value="6">6</option>
								<option value="7">7</option>
								<option value="8">8</option>
								<option value="9">9</option>
								<option value="10">10</option>
								<option value="11">11</option>
							</select>
						<td>
						<td>
							<label>Minute</label>
							<select id="startMin" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="00">00</option>
								<option value="10">10</option>
								<option value="20">20</option>
								<option value="30">30</option>
								<option value="40">40</option>
								<option value="50">50</option>
							</select>
						<td>
						<td>
							<label>AM/PM</label>
							<select id="startMeridiem" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="AM">AM</option>
								<option value="PM">PM</option>
							</select>
						</td>
					</tr>
					<tr>
						<td>
							<label>End Date</label>
							<input type="text" name="endDate" id="endDate" value="" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;"/>
						</td>
						<td>&nbsp;</td>
						<td>
							<label>Hour</label>
							<select id="endHour" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="12">12</option>
								<option value="1">1</option>
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="4">4</option>
								<option value="5">5</option>
								<option value="6">6</option>
								<option value="7">7</option>
								<option value="8">8</option>
								<option value="9">9</option>
								<option value="10">10</option>
								<option value="11">11</option>
							</select>
						<td>
						<td>
							<label>Minute</label>
							<select id="endMin" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="00">00</option>
								<option value="10">10</option>
								<option value="20">20</option>
								<option value="30">30</option>
								<option value="40">40</option>
								<option value="50">50</option>
							</select>
						<td>
						<td>
							<label>AM/PM</label>

							<select id="endMeridiem" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="AM">AM</option>
								<option value="PM">PM</option>
							</select>
						</td>
					</tr>
				</table>
				<table>
					<tr>
						<td>
							<label>Background Color</label>
						</td>
						<td>
							<div id="colorSelectorBackground"><div style="background-color: #333333; width:30px; height:30px; border: 2px solid #000000;"></div></div>
							<input type="hidden" id="colorBackground" value="#333333">
						</td>
						<td>&nbsp;&nbsp;&nbsp;</td>
						<td>
							<label>Text Color</label>
						</td>
						<td>
							<div id="colorSelectorForeground"><div style="background-color: #ffffff; width:30px; height:30px; border: 2px solid #000000;"></div></div>
							<input type="hidden" id="colorForeground" value="#ffffff">
						</td>
					</tr>
				</table>
			</fieldset>
			</form>
		</div>

		<div id="display-event-form" title="View Agenda Item">

		</div>

		<div id="edit-event-form" title="Edit Event">
			<p class="validateTips">All form fields are required.</p>
			<form>
			<fieldset>
				<label for="name">Event</label>
				<input type="text" name="what" id="_what" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;"/>
				<table style="width:100%; padding:5px;">
					<tr>
						<td>
							<label>Start Date</label>
							<input type="text" name="startDate" id="_startDate" value="" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;"/>
						</td>
						<td>&nbsp;</td>
						<td>
							<label>Hour</label>
							<select id="_startHour" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="12">12</option>
								<option value="1">1</option>
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="4">4</option>
								<option value="5">5</option>
								<option value="6">6</option>
								<option value="7">7</option>
								<option value="8">8</option>
								<option value="9">9</option>
								<option value="10">10</option>
								<option value="11">11</option>
							</select>
						<td>
						<td>
							<label>Minute</label>
							<select id="_startMin" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="0">00</option>
								<option value="10">10</option>
								<option value="20">20</option>
								<option value="30">30</option>
								<option value="40">40</option>
								<option value="50">50</option>
							</select>
						<td>
						<td>
							<label>AM/PM</label>
							<select id="_startMeridiem" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="AM">AM</option>
								<option value="PM">PM</option>
							</select>
						</td>
					</tr>
					<tr>
						<td>
							<label>End Date</label>
							<input type="text" name="endDate" id="_endDate" value="" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;"/>
						</td>
						<td>&nbsp;</td>
						<td>
							<label>Hour</label>
							<select id="_endHour" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="12">12</option>
								<option value="1">1</option>
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="4">4</option>
								<option value="5">5</option>
								<option value="6">6</option>
								<option value="7">7</option>
								<option value="8">8</option>
								<option value="9">9</option>
								<option value="10">10</option>
								<option value="11">11</option>
							</select>
						<td>
						<td>
							<label>Minute</label>
							<select id="_endMin" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="0">00</option>
								<option value="10">10</option>
								<option value="20">20</option>
								<option value="30">30</option>
								<option value="40">40</option>
								<option value="50">50</option>
							</select>
						<td>
						<td>
							<label>AM/PM</label>

							<select id="_endMeridiem" class="text ui-widget-content ui-corner-all" style="margin-bottom:12px; width:95%; padding: .4em;">
								<option value="AM">AM</option>
								<option value="PM">PM</option>
							</select>
						</td>
					</tr>
				</table>
				<table>
					<tr>
						<td>
							<label>Background Color</label>
						</td>
						<td>
							<div id="_colorSelectorBackground"></div>
							<input type="hidden" id="_colorBackground" value="">
						</td>
						<td>&nbsp;&nbsp;&nbsp;</td>
						<td>
							<label>Text Color</label>
						</td>
						<td>
							<div id="_colorSelectorForeground"></div>
							<input type="hidden" id="_colorForeground" value="">
						</td>
					</tr>
				</table>
                                <input type="hidden" id="_eventId" value=""/>
			</fieldset>
			</form>
		</div>
